package com.hmdp.service.impl;

import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import static com.hmdp.utils.RedisConstants.CACHE_SHOP_TYPE_KEY;
import static com.hmdp.utils.RedisConstants.CACHE_SHOP_TYPE_TTL;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public Result queryList() {
        // 1、查询Redis缓存
        List<String> range = redisTemplate.opsForList().range(CACHE_SHOP_TYPE_KEY, 0, -1);
        // 2、缓存命中，直接返回
        List<ShopType> shopTypeList = new ArrayList<>();
        if(range != null && !range.isEmpty()){
            for (String s : range){
                shopTypeList.add(JSONUtil.toBean(s, ShopType.class));
            }
            return Result.ok(shopTypeList);
        }
        // 3、缓存未命中，查询数据库
        List<ShopType> list = query().orderByAsc("sort").list();
        // 4、数据库不存在，返回错误
        if(list == null || list.isEmpty()){
            return Result.fail("无类型存在");
        }
        // 5、数据库存在，写入Redis
        for (ShopType shopType : list) {
            redisTemplate.opsForList().rightPush(CACHE_SHOP_TYPE_KEY, JSONUtil.toJsonStr(shopType));
        }
        redisTemplate.expire(CACHE_SHOP_TYPE_KEY, CACHE_SHOP_TYPE_TTL, TimeUnit.DAYS);
        // 6、返回
        return Result.ok(list);
    }
}
